package com.angle.im.server.domain;

import javax.websocket.Session;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author zhangwei
 * @date 2019/4/15 18:48
 * @desc 服务信息单例类
 */
public enum ImServer {
    /**
     *
     */
    INSTANCE;
    /**
     * 本机的服务ID
     * 用以区分集群下用户和服务器的对应关系
     */
    public final String LOCAL_SERVER_ID = UUID.randomUUID().toString();

    /**
     * 用线程安全的CopyOnWriteArraySet来存放客户端连接的信息
     */
    public final Map<String, Client> userClientMap = new ConcurrentHashMap<>();
    /**
     * 本地在线人数
     */
    public AtomicLong localUserNum = new AtomicLong(0);

    /**
     * 通过session获取userId
     * 这个方式比较low,可以通过其他方式实现
     *
     * @param session
     * @return
     */
    public String getUserId(Session session) {
        AtomicReference<String> platform = new AtomicReference<>(null);
        userClientMap.forEach((userId, client) -> {
            if (client.getSession() == session) {
                platform.set(client.getUserId());
            }
        });
        return platform.get();
    }

}
